﻿using NCP.Core;
using NCP.Core.Exceptions;
using NCP.Core.Extensions;
using NCP.Model;
using NCP.Service;
using NCP.Util;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using WebApp.Filters;
using NCP.Core.DataUtil;
using SqlSugar.Extensions;

namespace WebApp.Controllers
{
    [Authen]
    public class ReportController : Controller
    {
        private ReportService _service;

        public ReportController(ReportService service)
        {
            _service = service;
        }

        //全院统计
        public ActionResult WholeReport()
        {
            return View();
        }

        public ActionResult GetWholeList()
        {
            Expressionable<VDrugCompare> exp = new Expressionable<VDrugCompare>();
            int pageIndex = 1;
            int pageSize = 20;
            string gpCode = Request["GpCode"];
            string setpc= Request["setpc"];
            //if (string.IsNullOrEmpty(gpCode))
            //{
            //    List<VDrugCompare> lst = new List<VDrugCompare>();
            //    LayData rst = new LayData("0", "获取成功", lst, 0);

            //    return Content(JsonConvert.SerializeObject(rst));
            //}
            if (!string.IsNullOrEmpty(gpCode)) exp.And(t=>t.GpCode== gpCode);
            exp.AndIF(!string.IsNullOrEmpty(Request["drugCode"]),t=>t.DrugCode== Request["drugCode"]);
            if (!string.IsNullOrEmpty(Request.Form["page"]))
            {
                pageIndex = Convert.ToInt32(Request.Form["page"]);
            }
            if (!string.IsNullOrEmpty(Request.Form["limit"]))
            {
                pageSize = Convert.ToInt32(Request.Form["limit"]);
            }
            string iscomplete = Request["IsComplete"];
            exp.AndIF("1".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, t.TaskQty, t.UseNum) && t.UseRatio>=t.TaskRatio);
            exp.AndIF("0".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, 0, t.TaskQty - 1)||t.UseRatio<t.TaskRatio);
            PageModel pageModel = new PageModel() { PageIndex = pageIndex, PageSize = pageSize };
            List<VDrugCompare> dataList = _service.GetList(setpc,exp, pageModel);
            LayData ht = new LayData("0", "获取成功", dataList, pageModel.TotalCount);

            return Content(JsonConvert.SerializeObject(ht));
        }
        //全院采购统计
        public ActionResult WholePurReport()
        {
            return View();
        }

        public ActionResult GetWholePurList(string gpCode, string drugcode,string beginDate,string endDate)
        {
            Expressionable<VPurDrugCompare> exp = new Expressionable<VPurDrugCompare>();
            int pageIndex = 1;
            int pageSize = 20;
           
           
            //if (string.IsNullOrEmpty(gpCode))
            //{
            //    List<VDrugCompare> lst = new List<VDrugCompare>();
            //    LayData rst = new LayData("0", "获取成功", lst, 0);

            //    return Content(JsonConvert.SerializeObject(rst));
            //}
            if (!string.IsNullOrEmpty(gpCode)) exp.And(t => t.GpCode == gpCode);
            exp.AndIF(!string.IsNullOrEmpty(drugcode), t => t.DrugCode == drugcode);
            if (!string.IsNullOrEmpty(Request.Form["page"]))
            {
                pageIndex = Convert.ToInt32(Request.Form["page"]);
            }
            if (!string.IsNullOrEmpty(Request.Form["limit"]))
            {
                pageSize = Convert.ToInt32(Request.Form["limit"]);
            }
            
            string iscomplete = Request["IsComplete"];
            //exp.AndIF("1".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, t.TaskQty, t.UseNum) && t.UseRatio >= t.TaskRatio);
            //exp.AndIF("0".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, 0, t.TaskQty - 1) || t.UseRatio < t.TaskRatio);
            PageModel pageModel = new PageModel() { PageIndex = pageIndex, PageSize = pageSize };
            List<VPurDrugCompare> dataList = _service.GetVPurDrugList(beginDate, endDate, exp, pageModel);
            LayData ht = new LayData("0", "获取成功", dataList, pageModel.TotalCount);

            return Content(JsonConvert.SerializeObject(ht));
        }

        public ActionResult ExportWhole()
        {
            Expressionable<VDrugCompare> exp = new Expressionable<VDrugCompare>();
            string setpc = Request["setpc"];
            int pageIndex = 1;
            int pageSize = 100000;
            string gpCode = Request["GpCode"];
            //exp.And(t => t.GpCode == gpCode);
            if (!string.IsNullOrEmpty(gpCode)) exp.And(t => t.GpCode == gpCode);
            exp.AndIF(!string.IsNullOrEmpty(Request["drugCode"]), t => t.DrugCode == Request["drugCode"]);
            string iscomplete = Request["IsComplete"];
            exp.AndIF("1".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, t.TaskQty, t.UseNum) );
            exp.AndIF("0".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, 0, t.TaskQty - 1));
            PageModel pageModel = new PageModel() { PageIndex = pageIndex, PageSize = pageSize };
            List<VDrugCompare> dataList = _service.GetList(setpc,exp, pageModel);
            string filename = ExcelHelper.ExportToExcel(dataList, "“4+7”集采药品使用监测表（按全院统计）");
            return File(filename, "application/vnd.ms-excel", "“4+7”集采药品使用监测表（按全院统计）.xls");
        }


        //任务科室统计
        public ActionResult DeptReport()
        {
            return View();
        }

        public ActionResult GetDeptList()
        {
            Expressionable<VDeptDrugCompare> exp = new Expressionable<VDeptDrugCompare>();
            int pageIndex = 1;
            int pageSize = 20;
            string gpCode = Request["GpCode"];
            string setpc = Request["setpc"];//批次筛选
            string DeptCode = Request["DeptCode"];
            //if (string.IsNullOrEmpty(gpCode))
            //{
            //    List<VDeptDrugCompare> lst = new List<VDeptDrugCompare>();
            //    LayData rst = new LayData("0", "获取成功", lst, 0);

            //    return Content(JsonConvert.SerializeObject(rst));
            //}
            //exp.And(t => t.GpCode == gpCode);
            if (!string.IsNullOrEmpty(gpCode)) exp.And(t => t.GpCode == gpCode);
            exp.AndIF(!string.IsNullOrEmpty(Request["drugCode"]), t => t.DrugCode == Request["drugCode"]);
            if (string.IsNullOrEmpty(Request["DeptCode"]))
            {
                string IsAllMissionDeptOper = ConfigurationManager.AppSettings["IsAllMissionDeptOper"].ToString();//获取是否查看全部科室任务量
                string GetRoleSql = string.Format(" select e.RoleCode from MemberInRole l left join Role e on e.Id = l.RoleId where l.Code = '{0}'", MemberUtil.CurrentMember.Code);//根据工号获取角色
                SqlSugarClient _client = DbHelper.GetSqlSugarClient();
                string role = _client.Ado.GetString(GetRoleSql);


                if (IsAllMissionDeptOper.IndexOf(role) < 0)//如果没有配置该角色，则显示所有任务科室
                {

                    var users = _service.getUserDeptCode(MemberUtil.CurrentMember.Code);
                    exp.And(t => SqlFunc.ContainsArray(users, t.DeptCode));
                }
            }
            else
            {
                
                exp.And( t => t.DeptCode == Request["DeptCode"]);
            }
           
            string iscomplete = Request["IsComplete"];
            exp.AndIF("1".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, t.DeptQty, t.UseNum));
            exp.AndIF("0".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, 0, t.DeptQty - 1));
            if (!string.IsNullOrEmpty(Request.Form["page"]))
            {
                pageIndex = Convert.ToInt32(Request.Form["page"]);
            }
            if (!string.IsNullOrEmpty(Request.Form["limit"]))
            {
                pageSize = Convert.ToInt32(Request.Form["limit"]);
            }
            PageModel pageModel = new PageModel() { PageIndex = pageIndex, PageSize = pageSize };
            List<VDeptDrugCompare> dataList = _service.GetDeptList(setpc,exp, pageModel);
            LayData ht = new LayData("0", "获取成功", dataList, pageModel.TotalCount);

            return Content(JsonConvert.SerializeObject(ht));
        }
        //所有科室统计
        public ActionResult DeptALLReport()
        {
            return View();
        }
        public ActionResult GetALLDeptList()
        {
            Expressionable<VALLDeptDrugCompare> exp = new Expressionable<VALLDeptDrugCompare>();
            int pageIndex = 1;
            int pageSize = 20;
            string gpCode = Request["GpCode"];
            string setpc = Request["setpc"];//批次筛选
            //if (string.IsNullOrEmpty(gpCode))
            //{
            //    List<VDeptDrugCompare> lst = new List<VDeptDrugCompare>();
            //    LayData rst = new LayData("0", "获取成功", lst, 0);

            //    return Content(JsonConvert.SerializeObject(rst));
            //}
            //exp.And(t => t.GpCode == gpCode);
            if (!string.IsNullOrEmpty(gpCode)) exp.And(t => t.GpCode == gpCode);
            exp.AndIF(!string.IsNullOrEmpty(Request["drugCode"]), t => t.DrugCode == Request["drugCode"]);
            exp.AndIF(!string.IsNullOrEmpty(Request["DeptCode"]), t => t.DeptCode == Request["DeptCode"]);
            string iscomplete = Request["IsComplete"];
            exp.AndIF("1".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, t.TaskQty, t.UseNum));
            exp.AndIF("0".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, 0, t.TaskQty - 1));
            if (!string.IsNullOrEmpty(Request.Form["page"]))
            {
                pageIndex = Convert.ToInt32(Request.Form["page"]);
            }
            if (!string.IsNullOrEmpty(Request.Form["limit"]))
            {
                pageSize = Convert.ToInt32(Request.Form["limit"]);
            }
            PageModel pageModel = new PageModel() { PageIndex = pageIndex, PageSize = pageSize };
            List<VALLDeptDrugCompare> dataList = _service.GetALLDeptList(setpc, exp, pageModel);
            LayData ht = new LayData("0", "获取成功", dataList, pageModel.TotalCount);

            return Content(JsonConvert.SerializeObject(ht));
        }
        //集采药品任务科室统计
        public ActionResult ExportDept()
        {
            Expressionable<VDeptDrugCompare> exp = new Expressionable<VDeptDrugCompare>();
            int pageIndex = 1;
            int pageSize = 100000;
            string gpCode = Request["GpCode"];
            string setpc = Request["setpc"];//批次筛选
            string DeptCode = Request["DeptCode"];
            //if (string.IsNullOrEmpty(gpCode))
            //{
            //    List<VDeptDrugCompare> lst = new List<VDeptDrugCompare>();
            //    LayData rst = new LayData("0", "获取成功", lst, 0);

            //    return Content(JsonConvert.SerializeObject(rst));
            //}
            if (!string.IsNullOrEmpty(gpCode)) exp.And(t => t.GpCode == gpCode);
            if (!string.IsNullOrEmpty(Request["drugCode"])) exp.And(t => t.DrugCode == Request["drugCode"]);
            if (!string.IsNullOrEmpty(Request["DeptCode"])) exp.And(t => t.DeptCode == Request["DeptCode"]);
            //exp.AndIF(!string.IsNullOrEmpty(Request["drugCode"]), t => t.DrugCode == Request["drugCode"]);
            //exp.AndIF(!string.IsNullOrEmpty(Request["DeptCode"]), t => t.DeptCode == Request["DeptCode"]);
            string iscomplete = Request["IsComplete"];
            exp.AndIF("1".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, t.DeptQty, t.UseNum));
            exp.AndIF("0".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, 0, t.DeptQty - 1));
            PageModel pageModel = new PageModel() { PageIndex = pageIndex, PageSize = pageSize };
            List<VDeptDrugCompare> dataList = _service.GetDeptList(setpc,exp, pageModel);
            string filename = ExcelHelper.ExportToExcel(dataList, "“4+7”集采药品使用监测表（按科室统计）");
            return File(filename, "application/vnd.ms-excel", "“4+7”集采药品使用监测表（按科室统计）.xls");
        }
        //集采药品所有科室统计
        public ActionResult ExportALLDept()
        {
            Expressionable<VALLDeptDrugCompare> exp = new Expressionable<VALLDeptDrugCompare>();
            int pageIndex = 1;
            int pageSize = 1000000;
            string gpCode = Request["GpCode"];
            string setpc = Request["setpc"];//批次筛选
            //if (string.IsNullOrEmpty(gpCode))
            //{
            //    List<VDeptDrugCompare> lst = new List<VDeptDrugCompare>();
            //    LayData rst = new LayData("0", "获取成功", lst, 0);

            //    return Content(JsonConvert.SerializeObject(rst));
            //}
            //exp.And(t => t.GpCode == gpCode);
            if (!string.IsNullOrEmpty(gpCode)) exp.And(t => t.GpCode == gpCode);
            exp.AndIF(!string.IsNullOrEmpty(Request["drugCode"]), t => t.DrugCode == Request["drugCode"]);
            exp.AndIF(!string.IsNullOrEmpty(Request["DeptCode"]), t => t.DeptCode == Request["DeptCode"]);
            string iscomplete = Request["IsComplete"];
            exp.AndIF("1".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, t.TaskQty, t.UseNum));
            exp.AndIF("0".Equals(iscomplete), t => SqlFunc.Between(t.UseNum, 0, t.TaskQty - 1));
            if (!string.IsNullOrEmpty(Request.Form["page"]))
            {
                pageIndex = Convert.ToInt32(Request.Form["page"]);
            }
            if (!string.IsNullOrEmpty(Request.Form["limit"]))
            {
                pageSize = Convert.ToInt32(Request.Form["limit"]);
            }
            PageModel pageModel = new PageModel() { PageIndex = pageIndex, PageSize = pageSize };
            List<VALLDeptDrugCompare> dataList = _service.GetALLDeptList(setpc, exp, pageModel);
           
            string filename = ExcelHelper.ExportToExcel(dataList, "“4+7”集采药品所有科室使用监测表（按科室统计）");
            return File(filename, "application/vnd.ms-excel", "“4+7”集采药品所有科室使用监测表（按科室统计）.xls");
        }
        //同品种统计
        public ActionResult VarietyReport()
        {
            return View();
        }

        public ActionResult GetVarietyList()
        {
            Expressionable<VVarietyDrugCompare> exp = new Expressionable<VVarietyDrugCompare>();
            int pageIndex = 1;
            int pageSize = 20;
            string gpCode = Request["GpCode"];
            if (string.IsNullOrEmpty(gpCode))
            {
                List<VVarietyDrugCompare> lst = new List<VVarietyDrugCompare>();
                LayData rst = new LayData("0", "获取成功", lst, 0);

                return Content(JsonConvert.SerializeObject(rst));
            }
            exp.And(t => t.GpCode == gpCode);
            exp.AndIF(!string.IsNullOrEmpty(Request["drugCode"]), t => t.DrugCode == Request["drugCode"]);
            if (!string.IsNullOrEmpty(Request.Form["page"]))
            {
                pageIndex = Convert.ToInt32(Request.Form["page"]);
            }
            if (!string.IsNullOrEmpty(Request.Form["limit"]))
            {
                pageSize = Convert.ToInt32(Request.Form["limit"]);
            }
            PageModel pageModel = new PageModel() { PageIndex = pageIndex, PageSize = pageSize };
            List<VVarietyDrugCompare> dataList = _service.GetVarietyList(exp, pageModel);
            LayData ht = new LayData("0", "获取成功", dataList, pageModel.TotalCount);

            return Content(JsonConvert.SerializeObject(ht));
        }

        //同医生统计
        public ActionResult DocReport()
        {
            return View();
        }

        public ActionResult GetDocList()
        {
            Expressionable<VDocDrugCompare> exp = new Expressionable<VDocDrugCompare>();
            int pageIndex = 1;
            int pageSize = 20;
            string gpCode = Request["GpCode"];
            if (string.IsNullOrEmpty(gpCode))
            {
                List<VDocDrugCompare> lst = new List<VDocDrugCompare>();
                LayData rst = new LayData("0", "获取成功", lst, 0);

                return Content(JsonConvert.SerializeObject(rst));
            }
            exp.And(t => t.GpCode == gpCode);
            exp.AndIF(!string.IsNullOrEmpty(Request["drugCode"]), t => t.DrugCode == Request["drugCode"]);
            exp.AndIF(!string.IsNullOrEmpty(Request["DocCode"]), t => t.DoctorCode == Request["DocCode"]);
            if (!string.IsNullOrEmpty(Request.Form["page"]))
            {
                pageIndex = Convert.ToInt32(Request.Form["page"]);
            }
            if (!string.IsNullOrEmpty(Request.Form["limit"]))
            {
                pageSize = Convert.ToInt32(Request.Form["limit"]);
            }
            PageModel pageModel = new PageModel() { PageIndex = pageIndex, PageSize = pageSize };
            List<VDocDrugCompare> dataList = _service.GetDocList(exp, pageModel);
            LayData ht = new LayData("0", "获取成功", dataList, pageModel.TotalCount);

            return Content(JsonConvert.SerializeObject(ht));
        }

        public ActionResult ExportDoc()
        {
            Expressionable<VDocDrugCompare> exp = new Expressionable<VDocDrugCompare>();
            int pageIndex = 1;
            int pageSize = 20;
            string gpCode = Request["GpCode"];
            if (string.IsNullOrEmpty(gpCode))
            {
                List<VDocDrugCompare> lst = new List<VDocDrugCompare>();
                LayData rst = new LayData("0", "获取成功", lst, 0);

                return Content(JsonConvert.SerializeObject(rst));
            }
            exp.And(t => t.GpCode == gpCode);
            exp.AndIF(!string.IsNullOrEmpty(Request["drugCode"]), t => t.DrugCode == Request["drugCode"]);
            exp.AndIF(!string.IsNullOrEmpty(Request["DocCode"]), t => t.DoctorCode == Request["DocCode"]);
            PageModel pageModel = new PageModel() { PageIndex = pageIndex, PageSize = pageSize };
            List<VDocDrugCompare> dataList = _service.GetDocList(exp, pageModel);
            string filename = ExcelHelper.ExportToExcel(dataList, "“4+7”集采药品使用监测表（按医生统计）");
            return File(filename, "application/vnd.ms-excel", "“4+7”集采药品使用监测表（按医生统计）.xls");
        }

        public ActionResult GetEcharts1()
        {
            LayData ht = new LayData("0", "获取成功");
            try
            {
                ht.data = _service.GetEcharts1();
            }
            catch (Exception ex)
            {
                MessageException.CatchException(ex, ht);
            }

            return Content(ht.JsonToString(), "application/json");
        }
        public ActionResult GetEcharts2()
        {
            LayData ht = new LayData("0", "获取成功");
            try
            {

                var list= _service.GetEcharts1();
                dynamic data = new {
                    wc = list.FindAll(t=>t.iNum==0).Count,
                    wwc= list.FindAll(t => t.iNum != 0).Count
                };
                ht.data = data;
            }
            catch (Exception ex)
            {
                MessageException.CatchException(ex, ht);
            }

            return Content(ht.JsonToString(), "application/json");
        }
        public ActionResult GetEcharts3()
        {
            LayData ht = new LayData("0", "获取成功");
            try
            {
                ht.data = _service.GetEcharts4();
            }
            catch (Exception ex)
            {
                MessageException.CatchException(ex, ht);
            }

            return Content(ht.JsonToString(), "application/json");
        }

        //首页预警，未完成药品信息
        public ActionResult GetWholeWarnList()
        {
            string IsAllMissionDeptOper = ConfigurationManager.AppSettings["IsAllMissionDeptOper"].ToString();//获取是否查看全部科室任务量
            int days= ConfigurationManager.AppSettings["CountDownTime"].ToString().ObjToInt();
            string GetRoleSql = string.Format(" select e.RoleCode from MemberInRole l left join Role e on e.Id = l.RoleId where l.Code = '{0}'", MemberUtil.CurrentMember.Code);//根据工号获取角色
            SqlSugarClient _client = DbHelper.GetSqlSugarClient();
            string role = _client.Ado.GetString(GetRoleSql);

            
            if (IsAllMissionDeptOper.IndexOf(role) < 0)//如果没有配置该角色，则只显示该用户所在科室的药品任务信息
            {
                Expressionable<VDeptDrugCompare> exp = new Expressionable<VDeptDrugCompare>();
                var users = _service.getUserDeptCode(MemberUtil.CurrentMember.Code);
                exp.And(t => SqlFunc.ContainsArray(users, t.DeptCode));
                exp.And(t => SqlFunc.Between(t.UseNum, 0, t.TaskQty - 1) || t.UseRatio < t.TaskRatio);
                List<VDeptDrugCompare> dataList = _service.GetDeptWarnList(days, exp);
                LayData ht = new LayData("0", "获取成功", dataList, dataList.Count);
                return Content(JsonConvert.SerializeObject(ht));
            }
            else {
                Expressionable<VDrugCompare> exp = new Expressionable<VDrugCompare>();
                exp.And(t => SqlFunc.Between(t.UseNum, 0, t.TaskQty - 1) || t.UseRatio < t.TaskRatio);
                List<VDrugCompare> dataList = _service.GetWholeWarnList(exp, days);
                LayData ht = new LayData("0", "获取成功", dataList, dataList.Count);
                return Content(JsonConvert.SerializeObject(ht));
            }
        }

        public ActionResult GetDeptWarnList()
        {
            int days = ConfigurationManager.AppSettings["CountDownTime"].ToString().ObjToInt();
            Expressionable<VDeptDrugCompare> exp = new Expressionable<VDeptDrugCompare>();
            exp.And(t => SqlFunc.Between(t.UseNum, 0, t.TaskQty - 1) || t.UseRatio < t.TaskRatio);
            List<VDeptDrugCompare> dataList = _service.GetDeptWarnList(days, exp);
            LayData ht = new LayData("0", "获取成功", dataList, dataList.Count);
            return Content(JsonConvert.SerializeObject(ht));
        }
    }
}